package com.zky.gulimall.coupon.service.impl;

import com.alibaba.fastjson.JSON;
import com.zky.common.utils.DateUtil;
import com.zky.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.zky.gulimall.coupon.service.SeckillSkuRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.coupon.dao.SeckillSessionDao;
import com.zky.gulimall.coupon.entity.SeckillSessionEntity;
import com.zky.gulimall.coupon.service.SeckillSessionService;
import org.springframework.util.CollectionUtils;


@Service("seckillSessionService")
@Slf4j
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Autowired
    private SeckillSkuRelationService relationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLast3DaySession() {
        List<SeckillSessionEntity> entityList = this.list(new QueryWrapper<SeckillSessionEntity>().between("start_time", getStartTime(), getEndTime()));
        if (!CollectionUtils.isEmpty(entityList)) {
            entityList = entityList.stream().map(item -> {
                List<SeckillSkuRelationEntity> entities = relationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", item.getId()));
                item.setRelationEntities(entities);
                return item;
            }).collect(Collectors.toList());
        }
        log.warn("getLast3DaySession result:{}", JSON.toJSONString(entityList));
        return entityList;
    }

    private LocalDateTime getStartTime() {
        LocalDate now = LocalDate.now();
        LocalDateTime startTime = LocalDateTime.of(now, LocalTime.MIN);
        startTime.format(DateTimeFormatter.ofPattern(DateUtil.NORMAL_FORMAT));
        return startTime;
    }

    private LocalDateTime getEndTime() {
        LocalDate now = LocalDate.now().plusDays(2);
        LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MAX);
        endTime.format(DateTimeFormatter.ofPattern(DateUtil.NORMAL_FORMAT));
        return endTime;
    }

}